const app = require("express").Router();
const fs = require('fs')
var multiparty = require('multiparty');

app.post("/uplod", (req, res) => {
  const form = new multiparty.Form(); // 表单 name
  form.encoding = "UTF-8"; // 设置编码
  form.uploadDir = "./assets"; // 设置临时文件中转站
  form.maxFilesSize = 2 * 1024 * 1024; // 2M  // 设置上传图片的最大内存
  form.parse(req, function (err, fields, files) {
    if (err) throw err; // fields 文件域对象        // files 图片文件
    var uploadUrl = "/images/";
    console.log(files);
    file = files["instructions"]; // 图片信息
    (originalFilename = file[0].originalFilename), // 1.jpg
      (tempath = file[0].path); // 临时的文件路径
    var timestamp = new Date().getTime();
    uploadUrl += timestamp + originalFilename; // /images/upload/12342314214521.jpg
    var newPath = "./public" + uploadUrl; // 最终的文件路径
    var fileRead = fs.createReadStream(tempath); // 可读流 可写流
    var fileWrite = fs.createWriteStream(newPath);
    fileRead.pipe(fileWrite); // pipe 管道输送 数据
    res.send({code:0,msg:'xxxx'})
    fileWrite.on("close", () => {
      // pipe 监听 关闭 删除临时文件夹里面的图片
      fs.unlinkSync(tempath);
      // http://139.186.153.243/node/public/images/
      // console.log(/images/1617262255109发甘塞_09.jpg,'uploadUrl')
      res.json({ code:0, msg:  `http://139.186.153.243/node/public${uploadUrl}` }); // msg uploadUrl
    });
  });
});


module.exports =  app